package com.yisu.expressway.api.web.interceptor;


import com.alibaba.fastjson.JSON;
import com.yisu.expressway.api.domain.config.SystemConfig;
import com.yisu.expressway.ewf.common.utils.HTTPClientUtil;
import com.yisu.expressway.ewf.common.web.JsonResult;
import com.yisu.expressway.ewf.entity.User;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import java.util.HashMap;
import java.util.Map;

import static com.yisu.expressway.ewf.common.enums.ResponseCode.TOKEN_NOT_EXIST;

/**
 * 切面拦截器
 * Created by zj on 2017/3/16.
 */
@Component
@Aspect
public class AuthVerifyAspect {
    @Resource
    private SystemConfig systemConfig;
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 拦截所有IAuthVerifyAnnotation注解方法
     */
    @Pointcut("execution(@com.yisu.expressway.api.web.interceptor.IAuthVerifyAnnotation * *(..))")
    public void controllerPointcut() {
    }

    @Around("controllerPointcut()")
    public Object controllerAround(ProceedingJoinPoint joinPoint) {
        try {
            // 获取接口的请求参数
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            for (int i = 0; i < signature.getParameterNames().length; i++) {
                if (signature.getParameterNames()[i].toLowerCase().equals("token")) {
                    String token = joinPoint.getArgs()[i] + "";
                    if (org.apache.commons.lang3.StringUtils.isEmpty(token)) {
                        return new JsonResult(TOKEN_NOT_EXIST.code, "token不能为空");
                    }
                    Map<String, String> param = new HashMap<>();
                    param.put("token", token);
                    String json=HTTPClientUtil.doPost(systemConfig.getGetUserInfoApiUrl(), param);
                    User user = JSON.parseObject(JSON.parseObject(json).getString("data"), User.class);
                    if (user == null) {
                        return new JsonResult(TOKEN_NOT_EXIST.code, "用户不存在，请尝试重新登陆");
                    }
                }
            }
            return joinPoint.proceed();
        } catch (Exception e) {
            logger.error("IAuthVerifyAnnotation权限验证注解拦截失败，异常信息：" + e.getMessage(), e);
        } catch (Throwable throwable) {
            logger.error("IAuthVerifyAnnotation权限验证注解拦截失败，异常信息：" + throwable.getMessage(), throwable);
        }
        return null;
    }
}
